package com.frontop.system.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frontop.common.domain.UserJurisdiction;
import com.frontop.common.util.JwtUtil;
import com.frontop.common.util.ResultJsonUtil;
import com.frontop.system.modules.sys.model.SysOrganization;
import com.frontop.system.modules.sys.model.SysOrganizationMenu;
import com.frontop.system.modules.sys.service.SysOrganizationMenuService;
import com.frontop.system.modules.sys.service.SysOrganizationService;
import com.frontop.system.modules.sys.vo.SysOrganizationVO;
import com.frontop.system.modules.user.service.TUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YangJia
 * @since 2022-01-10
 */
@RestController
@RequestMapping("/sys-organization")
public class SysOrganizationController {
    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private TUserService tUserService;
    @Autowired
    private SysOrganizationMenuService sysOrganizationMenuService;

    @ApiOperation(value = "组织列表")
    @PreAuthorize("hasAuthority('system:organization:list')")
    @PostMapping("/organizationList")
    public ResultJsonUtil<Object> organizationList(@RequestBody(required = false) SysOrganizationVO vo,
                                                   Authentication authentication, HttpServletRequest request) {
        Page<SysOrganization> page = new Page<>(vo.getPageNo(), vo.getPageSize());
        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        //获取当前登录用户基本权限信息
       UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        //只查询当前组织和下级组织
        queryWrapper.in("id",userJurisdiction.getLowerOrganizationIds());
        if(StringUtils.isNotEmpty(vo.getName())){
            queryWrapper.like("name",vo.getName());
        }
        if(vo.getPId() != null){
            queryWrapper.eq("p_id",vo.getPId());
        }
        queryWrapper.eq("status",1);
        page = sysOrganizationService.page(page,queryWrapper);
        return new ResultJsonUtil().success(page);
    }


    @ApiOperation(value = "组织树")
    @GetMapping("/organizationTree")
    public ResultJsonUtil<Object> organizationTree(Authentication authentication,HttpServletRequest request) {
        //获取当前登录用户基本权限信息
        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        return new ResultJsonUtil().success(sysOrganizationService.getOrgTree(userJurisdiction.getOrganizationId()));
    }

    @ApiOperation(value = "添加修改企业信息")
    @PostMapping("/addOrUpOrganization")
    @PreAuthorize("hasAuthority('system:organization:upOrAdd')")
    @Transactional
    public ResultJsonUtil<Object> addOrUpOrganization(@RequestBody(required = false) SysOrganization sysOrganization,HttpServletRequest request) {
        if(StringUtils.isEmpty(sysOrganization.getName())){
            return new ResultJsonUtil().customFail("企业不能为空");
        }
        //验证上级组织

        if((sysOrganization.getPId() == null || sysOrganization.getPId().equals(0)) && !sysOrganization.getLevel().equals(0)){
            return new ResultJsonUtil().customFail("上级企业必填");
        }else {
            if(sysOrganization.getId() != null){
                List<Integer> orgIds = sysOrganizationService.findAllChildNodeId(sysOrganization.getId());
                if(sysOrganization.getId().equals(sysOrganization.getPId()) || orgIds.contains(sysOrganization.getPId())){
                    return new ResultJsonUtil().customFail("上级企业等级不能小于当前企业");
                }
            }
        }

        //验证名重复
        QueryWrapper<SysOrganization> wrapper = new QueryWrapper();
        wrapper.eq("name",sysOrganization.getName());
        wrapper.eq("status",1);
        SysOrganization loSysOrganization = sysOrganizationService.getOne(wrapper);

        if(loSysOrganization != null){
            if(sysOrganization.getId() != null){
                if(!loSysOrganization.getId().equals(sysOrganization.getId())){
                    return new ResultJsonUtil().customFail("企业名重复");
                }
            }else {
                if(loSysOrganization.getName().equals(sysOrganization.getName())){
                    return new ResultJsonUtil().customFail("企业名重复");
                }
            }
        }

        if(sysOrganization.getId() != null){
            //删除菜单中间表
            Map<String,Object> map = new HashMap<>();
            map.put("org_id",sysOrganization.getId());
            List<Integer> menuIds = sysOrganizationMenuService.getMenuIdsByOrgId(sysOrganization.getId());
            sysOrganizationMenuService.removeByIds(menuIds);
        }else {
            sysOrganization.setCreateTime(new Date());
            sysOrganization.setStatus(1);
        }

        sysOrganizationService.saveOrUpdate(sysOrganization);

        for(Integer menuId:sysOrganization.getMenuList()){
            SysOrganizationMenu sysOrganizationMenu = new SysOrganizationMenu();
            sysOrganizationMenu.setMenuId(menuId);
            sysOrganizationMenu.setOrgId(sysOrganization.getId());
            sysOrganizationMenuService.save(sysOrganizationMenu);
        }

        return new ResultJsonUtil().success("请求成功");
    }

    @ApiOperation(value = "删除组织")
    @GetMapping("/deleteOrganizationById/{id}")
    @PreAuthorize("hasAuthority('system:organization:delete')")
    @Transactional
    public ResultJsonUtil<Object> deleteOrganizationById(@PathVariable("id") Integer id,HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        map.put("org_id",id);
        sysOrganizationMenuService.removeByMap(map);
        return new ResultJsonUtil().success(sysOrganizationService.deleteOrganization(id));
    }

    @ApiOperation(value = "获取组织拥有菜单权限")
    @GetMapping("/getMenuIdsByOrgId/{orgId}")
    public ResultJsonUtil<Object> getMenuIdsByOrgId(@PathVariable("orgId") Integer orgId, HttpServletRequest request) {

        List<Integer> menuIds = sysOrganizationMenuService.getSysMenuIdsByOrgId(orgId);

        return new ResultJsonUtil().success(menuIds);
    }

}